import API from "../../https/api";

const state = {
  state: [{ value: "1", label: "使用" }, { value: "0", label: "停用" }], //状态
  user_status: null, //用户状态
  user_sex: null, //用户性别
  role_status: null, //角色状态
  menu_status: null, //菜单状态
  dict_status: null, //字典状态
  log_oper_kind: null, //操作类型
  oper_status: null, //操作状态
  login_status: null, //登录状态
  menu_kind: null, //菜单类别
  dict_type: null, //字典类别
  json: {} // json格式
};

const mutations = {
  setDictFn: (state, json) => {
    state[json.key] = json.list;
  },
  setDictJson: (state, json) => {
    state.json[json.key] = json.json;
  }
};

const actions = {
  getDict({ state, commit, dispatch }, key) {
    if (!key || state[key]) {
      return;
    }
    let list = [],
      groupKey = null;
    return API.dictManage.selectCode({ dictCode: key }).then(res => {
      if (res.code == "1") {
        list = res.data;
        commit("setDictFn", { key, list });
        dispatch("getJson", key);
      }
    });
  },
  getJson({ state, commit }, key) {
    let list = state[key];
    if (!key || !list) {
      return null;
    }
    let json = {};
    for (let i in list) {
      json[list[i].dictCode] = list[i].dictName;
    }
    commit("setDictJson", { key, json });
  },
  getAll({ state, dispatch }, keys) {
    let arr = [];
    for (let k in keys) {
      if (!state.json[keys[k]]) {
        if (!state[keys[k]]) {
          arr.push(dispatch("getDict", keys[k]));
        } else {
          dispatch("getJson", keys[k]);
        }
      }
    }
    return Promise.all(arr);
  },
  clear({ state, commit }) {
    for (let k in state) {
      switch (k) {
        case "state":
          break;
        case "json":
          commit("setDictFn", { key: k, list: {} });
          break;
        default:
          commit("setDictFn", { key: k, list: null });
      }
    }
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
